package com.barbeque.mall.aspect;

import com.barbeque.mall.anno.Log;
import com.barbeque.mall.bean.BaseRespVo;
import com.barbeque.mall.bean.order.MarketOrder;
import com.barbeque.mall.bean.system.MarketAdmin;
import com.barbeque.mall.bean.system.MarketLog;
import com.barbeque.mall.service.SysLogService;
import com.barbeque.mall.service.mallmanagement.OrderService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.naming.AuthenticationException;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;

/**
 * @author 苏东宇
 * @since 2022/07/17 23:21
 */
@Aspect
@Component
public class LogAspect {



    @Autowired
    SysLogService sysLogService;
    @Autowired
    OrderService orderService;


    @Pointcut("@annotation(com.barbeque.mall.anno.Log)")
    public void myPointcut(){
    }


    @Around("myPointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {

        //获取方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Object[] args = joinPoint.getArgs();

        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        //创建一个日志实例
        MarketLog marketLog = new MarketLog();

        String remoteAddr ;
        //获取本地ip
        if (request.getHeader("x-forwarded-for") == null) {
            remoteAddr = request.getRemoteAddr();
        }else{
            remoteAddr = request.getHeader("x-forwarded-for");
        }
        //目前写死，可以使用shrio来实现

        //获取操作结果
        BaseRespVo proceed = (BaseRespVo) joinPoint.proceed(args);
        String errmsg = proceed.getErrmsg();
        int errno = proceed.getErrno();

        Subject subject = SecurityUtils.getSubject();
        try {

            MarketAdmin primaryPrincipal = (MarketAdmin) subject.getPrincipals().getPrimaryPrincipal();
            String username1 = primaryPrincipal.getUsername();
            marketLog.setAdmin(username1);
        }catch (Exception e){
            return BaseRespVo.errorNamePsg("用户名密码不正确");
        }


        //获取登录的管理员名
        // adminNickname = (String) request.getAttribute("adminNickname");

        //获取操作动作
        Log logAnnotation = method.getAnnotation(Log.class);
        String action = logAnnotation.action();
        int type = logAnnotation.type();
        int op = logAnnotation.op();

        marketLog.setIp(remoteAddr);

        marketLog.setAction(action);
        marketLog.setDeleted(false);
        marketLog.setAddTime(new Date(System.currentTimeMillis()));
        marketLog.setUpdateTime(new Date(System.currentTimeMillis()));
        //type默认是1,安全操作，订单操作是2
        marketLog.setType(type);
        if (errno == 0){
            marketLog.setStatus(true);
        }else {
            marketLog.setStatus(false);
        }
        //如果是安全操作的话,并且操作不是创建管理员的op=2，操作结果返回errmsg
        String username = null;
        if (type == 1 && op != 2){
            marketLog.setResult(errmsg);
        }else if (type == 1 && op == 2){
            //创建管理员操作返回新创建的管理员的姓名
            //获取管理员姓名
            for (Object arg : args) {
                MarketAdmin marketAdmin = (MarketAdmin) arg;
                username =  marketAdmin.getUsername();
            }
            marketLog.setResult(username);
        }

        //如果是订单操作，来获取切入点方法的形参orderId
        int orderId = 0;
        if(type == 2){
            // Map<Object,Object>[] orderArgs = (Map<Object, Object>[]) joinPoint.getArgs();
            // for (Map<Object, Object> orderArg : orderArgs) {
            //     if (orderArg.containsKey("orderId")){
            //         orderId = (int) orderArg.get("orderId");
            //     }
            // }

            for (Object arg : args) {
                Map<Object,Object> argMap = (Map<Object, Object>) arg;
                if (argMap.containsKey("orderId")){
                    orderId = (int) argMap.get("orderId");
                }
            }
            //根据orderId来查询订单编号，填入result中
            MarketOrder orderById = orderService.getOrderById(orderId);
            if (orderById != null){
                String orderSn = orderById.getOrderSn();
                marketLog.setResult("用户编号为" + orderSn );
            }

        }




        int log = sysLogService.createLog(request, joinPoint, marketLog);
        return proceed;
    }

}
